﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Ext.Net;
using Ext.Net.MVC;
using WebEntities;
using WebEntities.Models.WebInfo;
using com.subb.WebInfo;

namespace WebAdmin.Controllers
{
    [Authorize]
    public class AdvItemController : Controller
    {
        private const string ADVIMG_PATH = "AdvImgs/";

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAllAdvItemByPage(int suiteId, StoreRequestParameters parms)
        {
            WI_AdvItemDAL aidal = new WI_AdvItemDAL();
            WI_AdvSuiteDAL asdal = new WI_AdvSuiteDAL();
            int ttlCount;
            List<WI_AdvItem> wiaiList;
            if (suiteId == 0)
            {
                //获取全部
                wiaiList = aidal.GetAllAdvItems(parms.Start, parms.Limit, out ttlCount);
            }
            else
            {
                //按广告栏目获取
                wiaiList = aidal.GetAllAdvItems(suiteId, parms.Start, parms.Limit, out ttlCount);
            }
            List<AdvItem> adItemList = new List<AdvItem>();
            foreach (var wiad in wiaiList)
            {
                string suiteName = string.Empty;
                if (wiad.SuiteID.HasValue)
                {
                    WI_AdvSuite suite = asdal.GetAdvSuite(wiad.SuiteID.Value);
                    if (suite != null)
                    {
                        suiteName = suite.SuiteName;
                    }
                    AdvItem aditem = AdvItem.AsAdvItem(wiad, suiteName);
                    adItemList.Add(aditem);
                }
                
            }
            return this.Store(adItemList, ttlCount);
        }

        [HttpPost]
        public ActionResult DeleteAdvItem(List<AdvItem> delItems)
        {
            try
            {
                WI_AdvItemDAL aidal = new WI_AdvItemDAL();
                foreach (var aitem in delItems)
                {
                    aidal.RemoveAdvItem(aitem.AdvID);
                }
                return this.Direct(new { Success = true, Msg = "删除成功！" });
            }
            catch (Exception ex)
            {
                return this.Direct(new { Success = false, Msg = ex.InnerException != null ? ex.InnerException.Message : ex.Message });
            }
        }

        public ActionResult NewAdvItemWindow()
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "新建广告条目",
                Width = 700,
                Height = 400,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.PhoneAdd,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("CreateAdvItem"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            wnd.Render();
            return this.Direct();
        }

        public ActionResult CreateAdvItem()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateAdvItem(AdvItem adItem)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            try
            {
                WI_AdvItemDAL aidal = new WI_AdvItemDAL();
                string creator = Request.IsAuthenticated ? HttpContext.User.Identity.Name : "Anonymous";
                adItem.Creator = creator;
                adItem.Modifier = creator;
                int advId = aidal.CreateAdvItem(adItem);
                //上传广告图片
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb1 = fb.Get("PicUrl");
                    string savePath = string.Empty;
                    if (fpfb1 != null && fpfb1.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + ADVIMG_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb1.FileName);
                            savePath += "adimg" + "_" + advId + extName;
                            fpfb1.SaveAs(savePath);
                            //更新路径
                            string webpath = uploadVFolder + ADVIMG_PATH + "adimg" + "_" + advId + extName;
                            AdvItem updAd = AdvItem.AsAdvItem(aidal.GetAdvItem(advId), "");
                            updAd.PicUrl = webpath;
                            aidal.UpdateAdvItem(advId, updAd);
                        }
                    }
                }
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "广告条目创建成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }

        public ActionResult EditAdvItemWindow(int advId)
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "编辑广告条目",
                Width = 700,
                Height = 400,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.PhoneEdit,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("EditAdvItem"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            wnd.Loader.Params.Add(new Parameter("advId", advId.ToString()));
            wnd.Render();
            return this.Direct();
        }

        public ActionResult EditAdvItem(int advId)
        {
            WI_AdvItemDAL aidal = new WI_AdvItemDAL();
            WI_AdvItem wiaItem = aidal.GetAdvItem(advId);
            AdvItem adItem = AdvItem.AsAdvItem(wiaItem, "");
            return View(adItem);
        }

        [HttpPost]
        public ActionResult EditAdvItem(AdvItem adItem)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            try
            {
                WI_AdvItemDAL aidal = new WI_AdvItemDAL();
                aidal.UpdateAdvItem(adItem.AdvID, adItem);
                //上传广告图片
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb1 = fb.Get("UploadAdvPic");
                    string savePath = string.Empty;
                    if (fpfb1 != null && fpfb1.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + ADVIMG_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb1.FileName);
                            savePath += "adimg" + "_" + adItem.AdvID + extName;
                            fpfb1.SaveAs(savePath);
                            //更新路径
                            string webpath = uploadVFolder + ADVIMG_PATH + "adimg" + "_" + adItem.AdvID + extName;
                            AdvItem updAd = AdvItem.AsAdvItem(aidal.GetAdvItem(adItem.AdvID), "");
                            updAd.PicUrl = webpath;
                            aidal.UpdateAdvItem(adItem.AdvID, updAd);
                        }
                    }
                }
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "广告栏目更新成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }
    }
}
